﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.Text;
using Pfizer.China.Pass.Framework.Argument;
using System.Collections;

namespace SystemFrameWork
{
    public class SQLGenerator
    {

        public List<string> GenerateSaveSQL(SQLGenerationArgument arg)
        {
            DataTable table = arg.SourceTable;
            List<string> sqls = new List<string>();
            string tableName = table.TableName;
            List<string> updateCondition = arg.UpdateConditionColumns;
            List<string> notSetCols = arg.NotSetColumns;
            List<string> notInsertCols = arg.NotInsertColumns;
            foreach (DataRow row in table.Rows)
            {
                string beginCondition = "IF @@ROWCOUNT=0 BEGIN";
                string endCondition = "END";
                string insert = generateInsertSql(row, tableName, notInsertCols);
                string update = generateUpdateSql(row, tableName, updateCondition, notSetCols);
                sqls.Add(update + "\r\n" + beginCondition + "\r\n" + insert + "\r\n" + endCondition);
            }
            return sqls;
        }

        /// <summary>
        /// Generate the update sql 
        /// </summary>
        /// <param name="deletionKey">deletion key of table,such as Id or Code</param>
        /// <param name="tableName">the name of table will be deleted</param>
        /// <param name="deletionKeyValue">the value of deletion key</param>
        /// <param name="user">the user who does the deletion operation</param>
        /// <param name="deletionStatus">the value set in the Recordstatus column</param>
        /// <returns>the sql statement.</returns>
        public string GenerateDeletionSQL(string deletionKey, string tableName, List<string> deletionKeyValue, Type valueType, string user, string deletionStatus)
        {
            StringBuilder builder = new StringBuilder();
            foreach (string val in deletionKeyValue)
            {
                string SqlFormat = "UPDATE {0} SET RecordStatus='{1}', UpdatedBy='{2}', UpdatedOn='{3}' WHERE {4}={5};";
                string delSql = string.Empty;
                if (valueType == typeof(int))
                {
                    delSql = string.Format(SqlFormat, tableName, deletionStatus, user, DateTime.Now, deletionKey, val);
                }
                else
                {
                    delSql = string.Format(SqlFormat, tableName, deletionStatus, user, DateTime.Now, deletionKey, addQuotation(val));
                }
                builder.Append(delSql);
                builder.Append("\r\n");
            }
            return builder.ToString();
        }

        public string GenerateDeletionSQL(string tableName, string user, string deletionStatus, Hashtable whereCondtionValue)
        {
            StringBuilder builder = new StringBuilder();
            string SqlFormat = "UPDATE {0} SET RecordStatus='{1}', UpdatedBy='{2}', UpdatedOn='{3}' WHERE {4};";
            foreach (string column in whereCondtionValue.Keys)
            {
                builder.Append(addBracket(column));
                builder.Append(" = ");
                builder.Append(addQuotation(whereCondtionValue[column]));
                builder.Append(" And ");
            }
            string where = builder.ToString();
            where = where.Remove(where.Length - 4);
            string deleteSql = String.Format(SqlFormat, tableName, deletionStatus, user, DateTime.Now, where);
            return deleteSql;
        }

        public string GenerateInsertSQL(string tableName, List<KeyValuePair<string, object>> columnValues)
        {
            string insertTemp = "Insert into {0} ({1}) Values ({2})";
            StringBuilder columnList = new StringBuilder();
            StringBuilder valueList = new StringBuilder();
            foreach (KeyValuePair<string, object> key in columnValues)
            {
                columnList.Append(addBracket(key.Key));
                columnList.Append(",");
                valueList.Append(addQuotation(key.Value));
                valueList.Append(",");
            }
            columnList.Remove(columnList.Length - 1, 1);
            valueList.Remove(valueList.Length - 1, 1);
            string columns = columnList.ToString();
            string values = valueList.ToString();
            string insert = string.Format(insertTemp, tableName, columns, values);
            return insert;
        }

        private string generateInsertSql(DataRow row, string tableName, List<string> notInsertValueColumns)
        {
            DataColumnCollection columns = row.Table.Columns;

            string sqlFormat = "Insert into {0} (";
            StringBuilder sql = new StringBuilder();
            sql.Append(string.Format(sqlFormat, tableName));
            for (int i = 0; i < columns.Count; i++)
            {
                if (!notInsertValueColumns.Contains(columns[i].ColumnName))//filter the column that is in notInsertValueColumns
                {
                    sql.Append(addBracket(columns[i].ColumnName) + ",");
                }
            }

            sql.Remove(sql.Length - 1, 1);
            sql.Append(") values (");

            for (int i = 0; i < columns.Count; i++)
            {
                if (!notInsertValueColumns.Contains(columns[i].ColumnName))//filter the column that is in notInsertValueColumns
                {
                    string val = null;
                    if (row[columns[i].ColumnName] != null && (!(row[columns[i].ColumnName] is DBNull)))
                    {
                        val = addQuotation(columns[i], row);
                    }
                    else
                    {
                        val = "NULL";
                    }
                    sql.Append(val + ",");
                }
            }

            sql.Remove(sql.Length - 1, 1);
            sql.Append(");");
            return sql.ToString();
        }

        /// <summary>
        /// must append the data in the same order to when invoking
        /// </summary>
        /// <param name="row"></param>
        /// <param name="tableName"></param>
        /// <returns></returns>
        public static string GenerateInsertSqlPre(DataTable tb, string tableName)
        {
            StringBuilder sbSql = new StringBuilder();

            sbSql.Append(string.Format("insert into {0}", tableName));

            StringBuilder sbColumns = new StringBuilder();
            for (int i = 0; i < tb.Columns.Count; i++)
            {
                sbColumns.Append(string.Format("[{0}]", tb.Columns[i].ColumnName));
                if (i != tb.Columns.Count - 1)
                {
                    sbColumns.Append(",");
                }
            }
            sbSql.Append(string.Format("({0})", sbColumns.ToString()));
            sbSql.Append(" select ");
            return sbSql.ToString();
        }

        private string generateUpdateSql(DataRow row, string desTableName, List<string> updateCondition, List<string> notSetValueColumns)
        {
            DataColumnCollection columns = row.Table.Columns;

            string updateSQL = string.Empty;
            //generate the set part

            StringBuilder sqlSet = new StringBuilder();
            for (int i = 0; i < columns.Count; i++)
            {
                if (!notSetValueColumns.Contains(columns[i].ColumnName))//filter the column that is in notInsertValueColumns
                {
                    string val = null;
                    if (row[columns[i].ColumnName] != null && (!(row[columns[i].ColumnName] is DBNull)))
                    {
                        val = addBracket(columns[i].ColumnName) + "=" + addQuotation(columns[i], row);
                    }
                    else
                    {
                        val = addBracket(columns[i].ColumnName) + "=" + "NULL";
                    }
                    sqlSet.Append(val + ",");
                }
            }
            sqlSet.Remove(sqlSet.Length - 1, 1);

            //Generate the update part

            string updateFormat = "UPDATE {0} SET ";
            string update = string.Format(updateFormat, desTableName);

            //Generate the where condition of update

            StringBuilder condition = new StringBuilder();
            foreach (string column in updateCondition)
            {
                if (row[column] is DBNull)
                {
                    condition.Append(addBracket(column) + " IS NULL AND ");
                }
                else
                {
                    condition.Append(addBracket(column) + "=" + addQuotation(columns[column], row) + " AND ");
                }
            }
            condition.Remove(condition.Length - 4, 4);
            string whereCondition = " WHERE " + condition.ToString() + ";";
            string updateState = update + sqlSet.ToString() + whereCondition;
            return updateState;

        }

        public string GenerateFKJoinDeletionSQL(List<EntityLinkInfo> fkRelationChain, string user, string deletionCode, Hashtable whereCondtion)
        {
            string targetTableName = fkRelationChain.FirstOrDefault().ChildTableName;
            string sourceTableName = fkRelationChain.LastOrDefault().ParentTableName;
            string updateSQLFormat = "Update {0} set RecordStatus='{1}', UpdatedBy='{2}', UpdatedOn='{3}' From {4}";
            string updateSQL = string.Format(updateSQLFormat, targetTableName, deletionCode, user, DateTime.Now, targetTableName);
            StringBuilder builder = new StringBuilder();
            foreach (EntityLinkInfo link in fkRelationChain)
            {
                builder.Append(generateInnerJoin(link));
            }
            updateSQL += builder.ToString();
            updateSQL += " " + generateWhereCondtion(whereCondtion, sourceTableName);
            return updateSQL;
        }

        private string generateWhereCondtion(Hashtable whereCondition, string alias)
        {
            StringBuilder builder = new StringBuilder();
            string template = "{0}.{1}={2}";
            foreach (string column in whereCondition.Keys)
            {
                builder.Append(String.Format(template, alias, column, addQuotation(whereCondition[column])));
            }
            string where = "Where " + builder.ToString();
            return where;
        }

        private string generateInnerJoin(EntityLinkInfo link)
        {
            string innerJoinFormat = " Inner Join {0} on {1}.{2}={3}.{4} ";
            string innerJoinSQL = String.Format(innerJoinFormat, link.ParentTableName, link.ParentTableName, link.PKName, link.ChildTableName, link.FKName);
            return innerJoinSQL;
        }

        /// <summary>
        /// Generate Select SQL
        /// </summary>
        /// <param name="tableName">Name of table to select</param>
        /// <param name="conditionKeyValue">Hashtable contains the key and value in where clause</param>
        /// <param name="selectColumns">The column list to select</param>
        /// <returns>Select SQL</returns>
        public string GenerateSelectSQL(string tableName, Hashtable conditionKeyValue, params string[] selectColumns)
        {
            string selectFormat = "Select {0} From {1} where {2}";
            StringBuilder builer = new StringBuilder();
            foreach (string col in conditionKeyValue.Keys)
            {
                builer.Append(col);
                builer.Append("=");
                builer.Append(addQuotation(conditionKeyValue[col]));
                builer.Append(" ");
                builer.Append("And ");
            }
            string condition = builer.ToString();
            condition = condition.Remove(condition.Length - 4);
            builer = new StringBuilder();
            string selectCols = string.Empty;
            if (selectColumns != null)
            {
                foreach (string col in selectColumns)
                {
                    builer.Append(col);
                    builer.Append(",");
                }
                selectCols = builer.ToString();
                selectCols = selectCols.Remove(selectCols.Length - 1);
            }
            else
            {
                builer.Append("*");
                selectCols = builer.ToString();
            }
            string select = string.Format(selectFormat, selectCols, tableName, condition);
            return select;
        }


        private string addQuotation(DataColumn column, DataRow row)
        {
            if (column.DataType == typeof(String) || column.DataType == typeof(DateTime))
            {
                return "'" + row[column.ColumnName].ToString() + "'";
            }
            else
            {
                return row[column.ColumnName].ToString();
            }
        }

        private string addQuotation(Object obj)
        {
            if (obj != null)
            {
                if (obj.GetType() == typeof(string) || obj.GetType() == typeof(DateTime))
                {
                    return "'" + obj.ToString() + "'";
                }
                else
                {
                    return obj.ToString();
                }
            }
            else
            {
                return "NULL";
            }

        }

        private string addBracket(string entity)
        {
            return "[" + entity + "]";
        }


    }
}
